package com.yuanqi.springboot_banksystem.service.impl;

import com.yuanqi.springboot_banksystem.entity.UserEntity;
import com.yuanqi.springboot_banksystem.mapper.UserMapper;
import com.yuanqi.springboot_banksystem.service.UserService;
import com.yuanqi.springboot_banksystem.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public Boolean register(UserEntity userEntity) {

        /**
         * 后端再校验
         */
        if (StringUtils.isEmpty(userEntity.getPassword())
                || StringUtils.isEmpty(userEntity.getUsername())
                || StringUtils.isEmpty(userEntity.getTel())){
            return false;
        }
        if (userMapper.selectUser(userEntity.getUsername())!=null){
            return false;
        }


        /**
         * 判断是否已经加密密码，没有则进行加密
         */
        if (userEntity.getSalt() == null || userEntity.getSalt().equals("")){

            String salt = MD5Util.getRandomSalt();

            userEntity.setSalt(salt);

            String md5Password = MD5Util.getMd5Password(userEntity.getPassword(),salt);

            userEntity.setPassword(md5Password);

        }

        /**
         * 数据预处理
         */
        userEntity.setBanlance(1000000.0);
        userEntity.setIs_cold(0);
        userEntity.setRole("user");
        userEntity.setIs_delete(0);

        Integer integer = userMapper.addUser(userEntity);

        if (integer == 1 || integer == 0) return true;

        return false;
    }

    @Override
    public Boolean login(String username, String password) {

        UserEntity userEntity = userMapper.selectUser(username);

        if (StringUtils.isEmpty(userEntity) || userEntity.getIs_delete() == 1){
            return false;
        }

        String realPassword = MD5Util.getMd5Password(password, userEntity.getSalt());

        if (realPassword.equals(userEntity.getPassword())){
            return true;
        }
        return false;
    }

    @Override
    public UserEntity selectUser(String username) {

        UserEntity userEntity = userMapper.selectUser(username);

        return userEntity;
    }

    @Override
    public Boolean updateUser(UserEntity userEntity) {

        Integer integer = userMapper.updateUser(userEntity);

        if (integer == 1) return true;

        return false;
    }

    @Override
    public List<UserEntity> selectAllUser() {

        List<UserEntity> userEntities = userMapper.selectAllUser();

        return userEntities;
    }
}
